import sys
from socket import *
from time import sleep


class TcpClient:
    def __init__(self):
        self.ADDR = ('176.17.13.23', 1211)
        self.tcp_socket = socket()
        self.tcp_connect()

    def tcp_connect(self):
        self.tcp_socket.connect(self.ADDR)

    def do_view(self):
        self.tcp_socket.send('1'.encode())
        data = self.tcp_socket.recv(1024)
        print(data.decode())

    def do_download(self):
        self.tcp_socket.send('2'.encode())
        name = input('请选择要下载的文件:')
        self.tcp_socket.send(name.encode())
        data = self.tcp_socket.recv(1024)
        if data == 'ok'.encode():
            file_lient = open(f'{name}', 'wb')
            while True:
                data = self.tcp_socket.recv(1024)
                if data == b'&&':
                    break
                file_lient.write(data)
            file_lient.close()
            print('文件下载成功')
        elif data == '##'.encode():
            print('文件不存在')

    def do_update(self):
        self.tcp_socket.send('3'.encode())
        name = input('请选择要上传的文件:')
        self.tcp_socket.send(name.encode())
        data = self.tcp_socket.recv(1024)
        if data == '##'.encode():
            print('文件已存在')
        elif data == b'ok':
            file = open(f'{name}', 'rb')
            while True:
                data = file.read(1024)
                if not data:
                    break
                self.tcp_socket.send(data)
            sleep(0.1)
            self.tcp_socket.send(b'&&')
            file.close()
            print('文件上传成功')

    def do_exit(self):
        self.tcp_socket.send('4'.encode())
        self.tcp_socket.close()
        sys.exit('谢谢使用')


class FtpClientView:
    def __init__(self):
        self.tcp_socket = TcpClient()

    def display(self):
        print('1.查看文件')
        print('2.下载文件')
        print('3.上传文件')
        print('4.退出')

    def select(self):
        mes = input('请输入选项：')
        if mes == '1':
            self.tcp_socket.do_view()
        elif mes == '2':
            self.tcp_socket.do_download()
        elif mes == '3':
            self.tcp_socket.do_update()
        elif mes == '4':
            self.tcp_socket.do_exit()
        else:
            print('请输入正确选项')

    def main(self):
        while True:
            self.display()
            self.select()


if __name__ == '__main__':
    ftp = FtpClientView()
    ftp.main()
